package menu

import (
	"context"
	"net/http"

	"go-zero-admin/apps/system/cmd/api/internal/svc"
	"go-zero-admin/apps/system/cmd/api/internal/types"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/pkg/constant"
	"go-zero-admin/pkg/ctxdata"

	"github.com/duke-git/lancet/v2/convertor"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetMenusRolesLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewGetMenusRolesLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *GetMenusRolesLogic {
	return &GetMenusRolesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *GetMenusRolesLogic) GetMenusRoles(req *types.GetMenusRolesReq) (resp *types.GetMenusRolesResp, err error) {
	// 获取新增、编辑菜单中的菜单树状列表
	listRpc, err := l.svcCtx.MenuRpc.GetMenuList(l.ctx, &syspb.GetMenuListReq{
		MenuType:        convertor.ToString(constant.MenuTypeMenu) + "," + convertor.ToString(constant.MenuTypeList),
		IsDataScope:     true,
		DataScopeUserId: ctxdata.GetUidFromCtx(l.ctx),
	})
	if err != nil {
		return nil, err
	}

	menuList := make([]*types.SysMenu, 0)
	for _, menuRpc := range listRpc.GetList() {
		var menu types.SysMenu
		_ = copier.Copy(&menu, menuRpc)

		menuList = append(menuList, &menu)
	}

	// 获取新增、编辑菜单中的角色列表
	roleListResp, err := l.svcCtx.RoleRpc.GetRoleList(l.ctx, &syspb.GetRoleListReq{
		Status:          convertor.ToString(constant.RoleStatusOn),
		IsDataScope:     true,
		DataScopeUserId: ctxdata.GetUidFromCtx(l.ctx),
	})
	if err != nil {
		return nil, err
	}

	roleList := make([]*types.SysRole, 0)
	for _, roleRpc := range roleListResp.GetList() {
		var role types.SysRole
		_ = copier.Copy(&role, roleRpc)

		roleList = append(roleList, &role)
	}

	return &types.GetMenusRolesResp{
		Roles: roleList,
		Menus: menuList,
	}, nil
}
